package com.mc.book.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.mc.book.dao.UserDao;
import com.mc.book.enums.ResponseEnum;
import com.mc.book.pojo.Result;
import com.mc.book.pojo.request.RequestUser;
import com.mc.book.redis.RedisService;
import com.mc.book.service.UserService;
import com.mc.book.utils.MD5;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
	private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    RedisService redis;

    @Autowired
    UserDao userDao;

    @Override
    public Result userReg(RequestUser request) {
        String validateCode = redis.getObject("validateCode:" + request.getValidatekey(),String.class);
        if(!request.getValidateCode().equals(validateCode)) return Result.fail(ResponseEnum.validateCode_fail.getCode(),ResponseEnum.validateCode_fail.getMessage());

        RequestUser user = userDao.getUserByPhone(request.getUser_phone());
        HashMap map = new HashMap<>();
        if(null == user){
            request.setUser_pass(MD5.md52(request.getUser_pass()));
            request.setReg_time(new Date());
            Boolean add = userDao.addUser(request);
            if(!add) return Result.fail(ResponseEnum.UP_SYSTEM_FAILURE.getCode(),ResponseEnum.UP_SYSTEM_FAILURE.getMessage());

            String key = UUID.randomUUID().toString().replaceAll("-", "");
            redis.add(key,"userToken:" + request.getUser_phone(), 30, TimeUnit.DAYS);
            request.setUser_pass(null);

            map.put("user", request);
            map.put("token", key);

        }else{
            return Result.fail(ResponseEnum.USER_HAVE.getCode(),ResponseEnum.USER_HAVE.getMessage());
        }
        return Result.success(ResponseEnum.success.getCode(),ResponseEnum.success.getMessage(),map);
    }

    @Override
    public Result userLogin(RequestUser request) {
        Integer errorLoginNum = redis.getObject("errorLogin:" + request.getUser_phone(),Integer.class);
        if(null == errorLoginNum) errorLoginNum = 0;

        if(3 < errorLoginNum){
            String validateCode = redis.getObject("validateCode:" + request.getValidatekey(),String.class);
            if(!request.getValidateCode().equals(validateCode)) return Result.fail(ResponseEnum.validateCode_fail.getCode(),ResponseEnum.validateCode_fail.getMessage());
        }

        RequestUser user = userDao.getUserByPhone(request.getUser_phone());
        if(null == user) return Result.fail(ResponseEnum.USER_NO_HAVE.getCode(),ResponseEnum.USER_NO_HAVE.getMessage());

        request.setUser_pass(MD5.md52(request.getUser_pass()));
        if(!request.getUser_pass().equals(user.getUser_pass())){
            redis.add("errorLogin:" + request.getUser_phone(), errorLoginNum+1, 5, TimeUnit.MINUTES);
            return Result.success(ResponseEnum.USER_PASS_ERROR.getCode(),ResponseEnum.USER_PASS_ERROR.getMessage());
        }else{
            redis.delete("errorLogin:" + request.getUser_phone());
            String key = UUID.randomUUID().toString().replaceAll("-", "");
            redis.add(key,"userToken:" + request.getUser_phone() , 30, TimeUnit.DAYS);

            user.setUser_pass(null);
            HashMap map = new HashMap<>();
            map.put("user", user);
            map.put("token", key);
            return Result.success(ResponseEnum.success.getCode(),ResponseEnum.success.getMessage(),map);
        }

    }

    @Override
    public Result validateCode() {
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 20);
        //验证码的值
        String codeValue = circleCaptcha.getCode();
        System.out.println("验证码为："+codeValue);
        //将图片进行base64编码，并返回
        String imageBase64 = circleCaptcha.getImageBase64();
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        //将验证码的值存入redis并设置5分钟过期
        redis.add("validateCode:" + key, codeValue, 5, TimeUnit.MINUTES);
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("validateKey", key);
        codeMap.put("imageBase64", "data:image/png;base64," + imageBase64);
        return Result.success(codeMap);
    }

    @Override
    public void vipUpdate(RequestUser request,Integer goods_type) {
        Date up_vip_time;
        Calendar calendar = Calendar.getInstance();
        Date day_time = new Date();

        RequestUser user = userDao.getUserByPhone(request.getUser_phone());
        Date vip_time = user.getVip_time();
        if(null != vip_time){
            if(day_time.after(vip_time)) calendar.setTime(day_time); //会员日期已失效
            if(day_time.before(vip_time)) calendar.setTime(vip_time);//会员日期未失效
        }else {
            calendar.setTime(day_time);
        }

        if(1 == goods_type) calendar.add(Calendar.YEAR, 1); // 在当前基础上增加一月
        if(2 == goods_type) calendar.add(Calendar.MONTH, 1); // 在当前基础上增加一年
        up_vip_time = calendar.getTime();
        user.setVip_time(up_vip_time);
        user.setIs_vip(1);
        Boolean update = userDao.updateVip(user);
        if(update){
            log.info("会员购买成功," + user.getUser_phone() + ",会员到期时间:" + up_vip_time + ",购买类型:" + goods_type);
        }else log.error("会员购买失败," + user.getUser_phone() + ",会员到期时间:" + up_vip_time + ",购买类型:" + goods_type);
    }

    @Override
    public RequestUser getInfo(String user_phone) {
        return userDao.getUserByPhone(user_phone);
    }

    @Override
    public void openidUpDate(String user_phone, String openid) {
        Boolean update = userDao.updateOpenid(user_phone, openid);
        if(update){
            log.info("用户openid更新成功," + user_phone + ",openid:" + openid);
        }else log.error("用户openid更新失败," + user_phone+ ",openid:" + openid);
    }

}
